import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter_screen_capture/flutter_screen_capture.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await FlutterScreenCapture.initialize();
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool _isRunning = false;
  Uint8List _screenImageData;

  @override
  void initState() {
    super.initState();
    FlutterScreenCapture.addFrameListener((imageData) {
      print("receive new frame!");
      setState(() {
        _screenImageData = imageData;
      });
    });

    FlutterScreenCapture.isRunning.listen((state) {
      setState(() {
        _isRunning = state;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Column(children: [
          if(_screenImageData != null)
            Image.memory(_screenImageData, width: 200, height:300,),
          Center(child: OutlinedButton(
            child: Text(_isRunning ? "Stop" : "Start"),
            onPressed: () {
              _isRunning ? FlutterScreenCapture.stop() : FlutterScreenCapture.start();
            },),
          ),
        ],)
      ),
    );
  }
}
